package tema.pdm;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;

import android.content.Context;
import android.os.Environment;

public class Update extends Thread {
	String _oras;
	Integer _contor;
	int _tip;
	String string;
	OrasAdapter _adaptor; 
	Context _context;
	
	Update(int tip,String oras, Context context)
	{
		_oras = oras;
		_context = context;
		_tip = tip;
	}
	

	public boolean descarcare()
	{
		String taskUrl = "http://www.google.com/ig/api?weather="+_oras;
		try{
		URL url = new URL(taskUrl);
		
		InputStream stream = url.openStream();
		InputStreamReader str = new InputStreamReader(stream);
		string = "";
		char ch[] = new char[402];
		int i;
		i = str.read(ch, 0, 400);
		while(i!=-1)
		{
			string =string + String.copyValueOf(ch, 0, i);
			System.out.println("<<"+i+">|<"+string+">>");
			i = str.read(ch, 0, 400);
		}
		}catch(Exception e){e.printStackTrace(); return false;}
		return true;
	}
	
	public boolean salvare()
	{
		try{
			//salvare in fisier
			String file = Environment.getExternalStorageDirectory()+ "/Tema1PDM/";
				
			File filecheck = new File(file);
			if(!filecheck.isDirectory())
				filecheck.mkdirs();
			
			file = file+_oras+".txt";
			filecheck = new File(file);
			if(!filecheck.isFile())
				filecheck.createNewFile();
			
			System.out.println("<<fisierul de iesire: "+file);
			OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(filecheck));
			writer.write(string);
			writer.close();
			
			}catch(Exception e){e.printStackTrace(); return false;}
			return true;
	}
	
	public boolean verificare()
	{
		//am string si il verific
		return !string.contains("<problem_cause");
	}
	
	public void run()
	{
		if(_tip == 0){
			 //descarcare si scriere in fisier
			 // stim ca e bun, nu mai verificam
			if(descarcare())
				salvare();
			
			((ThreadDone)_context).threadDone();
		}
		
		if(_tip == 1){
			//descarcare si verificare corectitudine
			// nu va face nimic aici 
			//(stupid, dar nu vrea sa ii dau add din alt thread decat cel original)
			salvare();
			((ThreadDone)_context).threadDone();
		}
		
	}
}
